package com.hhq.sso.system.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.hhq.sso.auth.base.pojo.SystemUserInfo;
import com.hhq.sso.common.domain.UserInfo;
import com.hhq.sso.system.entity.Menu;
import com.hhq.sso.system.entity.RoleMenu;
import com.hhq.sso.system.entity.RoleScope;
import com.hhq.sso.system.mapper.MenuMapper;
import com.hhq.sso.system.service.IMenuService;
import com.hhq.sso.system.service.IRoleMenuService;
import com.hhq.sso.system.service.IRoleScopeService;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.node.ForestNodeMerger;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import lombok.AllArgsConstructor;

/**
 * 服务实现类
 *
 * @author Chill
 */
@Service
@AllArgsConstructor
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    private final IRoleMenuService roleMenuService;
    private final IRoleScopeService roleScopeService;
    private final static String PARENT_ID = "parentId";

    @Override
    public IPage<Menu> selectMenuPage(IPage<Menu> page, Menu menu) {
        return page.setRecords(baseMapper.selectMenuPage(page, menu));
    }

    @Override
    public List<Menu> lazyMenuList(Long parentId, Map<String, Object> param) {
        if (Func.isEmpty(Func.toStr(param.get(PARENT_ID)))) {
            parentId = null;
        }
        return baseMapper.lazyMenuList(parentId, param);
    }

    @Override
    public List<Menu> routes(String roleIds) {
        if (StringUtil.isBlank(roleIds)) {
            return null;
        }
        List<Menu> allMenus = baseMapper.allMenu();
        List<Menu> roleMenus = baseMapper.roleMenu(Func.toLongList(roleIds));
        List<Menu> routes = new LinkedList<>(roleMenus);
        roleMenus.forEach(roleMenu -> recursion(allMenus, routes, roleMenu));
        routes.sort(Comparator.comparing(Menu::getSort));
        return routes;
    }

    public void recursion(List<Menu> allMenus, List<Menu> routes, Menu roleMenu) {
        Optional<Menu> menu = allMenus.stream().filter(x -> Func.equals(x.getId(), roleMenu.getParentId())).findFirst();
        if (menu.isPresent() && !routes.contains(menu.get())) {
            routes.add(menu.get());
            recursion(allMenus, routes, menu.get());
        }
    }

    @Override
    public List<Menu> buttons(String roleIds) {
        List<Menu> buttons = baseMapper.buttons(Func.toLongList(roleIds));
        return baseMapper.buttons(Func.toLongList(roleIds));
    }

    @Override
    public List<Menu> tree() {
        return ForestNodeMerger.merge(baseMapper.tree());
    }

    @Override
    public List<Menu> grantTree(SystemUserInfo user) {
        return ForestNodeMerger.merge(user.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID) ? baseMapper.grantTree()
            : baseMapper.grantTreeByRole(Func.toLongList(user.getRoleIds())));
    }

    @Override
    public List<Menu> grantDataScopeTree(SystemUserInfo user) {
        return ForestNodeMerger
            .merge(user.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID) ? baseMapper.grantDataScopeTree()
                : baseMapper.grantDataScopeTreeByRole(Func.toLongList(user.getRoleIds())));
    }

    @Override
    public List<String> roleTreeKeys(String roleIds) {
        List<RoleMenu> roleMenus =
            roleMenuService.list(Wrappers.<RoleMenu>query().lambda().in(RoleMenu::getRoleId, Func.toLongList(roleIds)));
        return roleMenus.stream().map(roleMenu -> Func.toStr(roleMenu.getMenuId())).collect(Collectors.toList());
    }

    @Override
    public List<String> dataScopeTreeKeys(String roleIds) {
        List<RoleScope> roleScopes = roleScopeService
            .list(Wrappers.<RoleScope>query().lambda().in(RoleScope::getRoleId, Func.toLongList(roleIds)));
        return roleScopes.stream().map(roleScope -> Func.toStr(roleScope.getScopeId())).collect(Collectors.toList());
    }

    @Override
    public List<Kv> authRoutes(SystemUserInfo user) {
        if (Func.isEmpty(user)) {
            return null;
        }
        List<Menu> routes = baseMapper.authRoutes(Func.toLongList(user.getRoleIds()));
        List<Kv> list = new ArrayList<>();
        routes.forEach(route -> list
            .add(Kv.init().set(route.getPath(), Kv.init().set("authority", Func.toStrArray(route.getAlias())))));
        return list;
    }

}
